package cn.stylefeng.guns.modular.gridsystem.event;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import cn.stylefeng.guns.modular.gridsystem.event.param.CollectingDeviceInfo;
import cn.stylefeng.guns.modular.gridsystem.event.param.FaultLog;
import cn.stylefeng.guns.modular.gridsystem.event.param.SensorInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.io.File;
import java.util.Map;

/**
 * @author ssy
 * @date 2023/2/23 11:50
 */
@Component
@Slf4j
public class SendToClientListener {

    @Value("${third-push-event.url}")
    private String url;

    /**
     * 采集设备信息
     * @param event
     */
    @Async
    @EventListener
    public void onDeviceInfoEvent(CollectingDeviceInfoEvent event) {
        CollectingDeviceInfo collectingDeviceInfo = event.getCollectingDeviceInfo();
        log.info("onDeviceInfoEvent: {}",collectingDeviceInfo);

        Map<String, Object> map = BeanUtil.beanToMap(collectingDeviceInfo);
        final String post = HttpUtil.post(url + "/api/push/deviceStatus", map);
        log.info("采集设备信息推送结果: {}",post);

    }

    /**
     * 传感器信息
     * @param event
     */
    @Async
    @EventListener
    public void onChannelEvent(ChannelInfoEvent event) {
        SensorInfo sensorInfo = event.getSensorInfo();
        log.info("onChannelEvent: {}",sensorInfo);

        Map<String, Object> map = BeanUtil.beanToMap(sensorInfo);
        final String post = HttpUtil.post(url + "/api/push/sensorStatus", map);
        log.info("传感器信息推送结果: {}",post);
    }

    /**
     * 故障日志
     * @param event
     */
    @Async
    @EventListener(classes = {FaultLogEvent.class})
    public void onExceptionLogEvent(FaultLogEvent event) {
        FaultLog faultLog = event.getFaultLog();
        File file = new File(faultLog.getFilePath());
        log.info("故障日志事件: {}",faultLog);

        Map<String, Object> map = BeanUtil.beanToMap(faultLog);
        map.put("faultFile",file);
        if(FileUtil.exist(faultLog.getModelFilePath())){
            map.put("modelFile",new File(faultLog.getModelFilePath()));
        }
        final String post = HttpUtil.post(url + "/api/push/faultLog", map);
        log.info("故障日志推送结果: {}",post);

    }

}
